package linkedlist;

import java.util.StringJoiner;

public class ReverseLinkedList {

    public static void main(String[] args) {
        ListNode head = new ListNode(1);
        ListNode node2 = new ListNode(2);
        ListNode node3 = new ListNode(3);
        ListNode node4 = new ListNode(4);
        ListNode node5 = new ListNode(5);
        head.next = node2;
        node2.next = node3;
        node3.next = node4;
        node4.next = node5;

        out(head);
        ListNode head2 = reverse(head);
        out(head2);

        reverse(null);
    }

    public static ListNode reverse(ListNode head) {
        if (head == null) {
            return null;
        }

        ListNode prev = head;
        ListNode current = head.next;
        prev.next = null;

        while (current != null) {
            ListNode next = current.next;
            current.next = prev;
            prev = current;
            current = next;
        }

        return prev;
    }

    public static void out(ListNode head) {
        StringJoiner stringJoiner = new StringJoiner(" -> ");
        ListNode head2 = head;
        while (head2 != null) {
            stringJoiner.add(head2.val + "");
            head2 = head2.next;
        }
        System.out.println(stringJoiner);
    }

}


class ListNode {

    Object val;

    ListNode next;

    public ListNode(Object value) {
        this.val = value;
    }

}